<template>
  <div class="app-container">
    <el-form :inline="true">
      <el-form-item label="">
        <el-input v-model="queryParams.roleName" @keyup.enter.native="handleQuery('1')" placeholder="请输入角色名称" />
      </el-form-item>
      <el-form-item label="">
        <el-input v-model="queryParams.roleKey" @keyup.enter.native="handleQuery('1')" placeholder="请输入权限标识" />
      </el-form-item>
      <el-form-item label="" style="width: 90px">
        <el-select v-model="queryParams.status" placeholder="状态">
          <el-option
            v-for="item in statusOptions"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="">
        <el-date-picker
          v-model="dateRange"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="至"
          start-placeholder="创建开始日期"
          end-placeholder="创建结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery('1')">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="handleQuery('reset')">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb5">
      <el-col :span="1.5"><el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button></el-col>
      <el-col :span="1.5"><el-button type="success" :disabled="single" icon="el-icon-edit" @click="handleUpdate(null)">修改</el-button></el-col>
      <el-col :span="1.5"><el-button type="danger" :disabled="multiple" icon="el-icon-delete" @click="handleDelete(null)">删除</el-button></el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" />
      <el-table-column prop="roleName" label="角色名称" min-width="80px" />
      <el-table-column prop="roleKey" label="权限标识" min-width="60px" />
      <el-table-column prop="orderNum" label="显示顺序" min-width="40px" />
      <el-table-column prop="status" label="状态" min-width="50px">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-value="1" inactive-value="0" @change="handleStatusChange(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建日期" min-width="120px" />
      <el-table-column label="操作" min-width="120px">
        <template slot-scope="scope">
          <el-button type="text" size="mini" icon="el-icon-plus" @click="AssignUser(scope.row)">分配用户</el-button>
          <el-button type="text" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="text" size="mini" icon="el-icon-delete" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="handleQuery" />

    <el-dialog :visible.sync="dialogVisible" :title="title" width="650px">
      <el-form ref="edit" :model="form" :label-width="formLabelWidth">
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色名称">
              <el-input v-model="form.roleName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="权限标识">
              <el-input v-model="form.roleKey" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示顺序">
              <el-input-number v-model="form.orderNum" :min="1" :max="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="item in statusOptions" :key="item.dictValue" :label="item.dictValue">{{ item.dictLabel }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单权限">
              <el-tree
                ref="menu"
                :data="menuList"
                show-checkbox
                empty-text="正在加载，请稍后"
                node-key="id"
                :props="defaultProps"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import initData from '@/mixins/initData'
import { changeRoleStatus, addRole, updateRole } from '@/api/system/role'
import { listMenu, getMenuTreeSelect, getTreeSelectByRoleId } from '@/api/system/menu'

export default {
  mixins: [initData],
  data() {
    return {
      statusOptions: [],
      queryParams: {
        roleName: undefined,
        roleKey: undefined,
        status: undefined
      },
      formLabelWidth: '100px',
      formReset: {
        status: '1',
        orderNum: '1'
      },
      defaultProps: {
        children: 'children',
        label: 'menuName'
      },
      // 菜单列表
      menuList: []
    }
  },
  mounted() {
    this.handleQuery()
    this.getDict('status_normal').then(res => {
      this.statusOptions = res.data
    })
  },
  methods: {
    beforeInit() {
      this.base = '/system/role'
      this.modalName = '角色'
    },
    // 修改状态
    handleStatusChange(row) {
      const text = row.status === '0' ? '停用' : '启用'
      this.$confirm('确认要' + text + '【' + row.roleName + '】角色吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return changeRoleStatus(row.id, row.status)
      }).then(res => {
        this.msgSuccess(text + '成功')
      }).catch(() => {
        row.status = row.status === '0' ? '1' : '0'
      })
    },
    // 新增按钮
    handleAdd() {
      this.title = '新增角色'
      this.dialogVisible = true
      this.form = this.formReset
      this.getMenuList()
    },
    // 获取所有的菜单
    getMenuList() {
      listMenu().then(res => {
        // 将获取到的菜单列表处理为树结构
        this.menuList = this.handleTree(res.data)
      })
    },
    submitForm() {
      this.$refs['edit'].validate(valid => {
        if (valid) {
          this.form.menuIds = this.getAllCheckedMenus()
          if (!this.form.id) {
            addRole(this.form).then(() => this.msgSuccess('添加成功'))
          } else {
            updateRole(this.form).then(() => this.msgSuccess('修改成功'))
          }
          this.dialogVisible = false
          this.handleQuery()
        }
      })
    },
    // 获取选中的所有菜单
    getAllCheckedMenus() {
      // 获取目前半选中的节点的key（见https://element.eleme.cn/#/zh-CN/component/tree文档说明）
      const checkedMenuKeys = this.$refs['menu'].getHalfCheckedKeys()
      // 获取目前被选中的节点的key
      const halfCheckedKeys = this.$refs['menu'].getCheckedKeys()
      // 返回所有被选中和半选中的节点
      halfCheckedKeys.unshift.apply(halfCheckedKeys, checkedMenuKeys)
      return halfCheckedKeys
    },
    handleUpdate(row) {
      this.form = row || this.row
      this.dialogVisible = true
      this.title = '修改角色'
      this.$nextTick(() => {
        this.getMenuList()
        this.findRoleMenuTreeSelect(this.form.id)
      })
    },
    findRoleMenuTreeSelect(id) {
      getTreeSelectByRoleId(id).then(res => {
        this.$refs['menu'].setCheckedKeys(res.data)
      })
    },
    // 分配用户到选中的角色
    AssignUser(row) {
      console.log(row.id)
    }
  }
}

</script>

<style lang="scss" scoped>

</style>
